#include "SmokeSensor.h"
#include "TinyXML/tinyxml.h"
#include "ChineseEnglishMapping.h"
#include <QDebug>
#include <QVBoxLayout>
#include <QSplitter>

SmokeSensor::SmokeSensor()
{

}

void SmokeSensor::InitUI(const QString &fileName, QList<QPair<QWidget *, QString> > &widgets, QMap<int, QList<TableWidgetForm *> > &m_pTableWidgetFormMap)
{
    QString filePath = QString("%1/config/%2/%3")
            .arg(COMMONS->XmlPath)
            .arg(COMMONS->MachType)
            .arg(fileName);
    SmokeConnectStr _SmokeConnectStr;
    QList<QList<SmokeSensorstruct> > SmokeSensorstructList;
    Analysis(filePath,_SmokeConnectStr,SmokeSensorstructList);

    //添加第一个表
    QWidget* widget = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(widget);
    QSplitter *splitter = new QSplitter(Qt::Vertical, widget);
    splitter->setChildrenCollapsible(false);
    layout->addWidget(splitter);
    widgets.append(qMakePair(widget,QStringLiteral("tab0")));

    TableWidgetForm* _TableWidgetForm = new TableWidgetForm(widget);
    splitter->addWidget(_TableWidgetForm);
    _TableWidgetForm->setGroupBoxTitle(QString("%1_0").arg(fileName.left(fileName.size()-4)));

    //获取表头
    _TableWidgetForm->setTableWidgetHeaderLabels(COMMONS->getTableWidgetHeadLabels(fileName,_SmokeConnectStr.toFieldNames().split(',')));
    _TableWidgetForm->setTableWidgetHeaderType(_SmokeConnectStr.toFieldTypes());

    _TableWidgetForm->getTableWidget()->setRowCount(1);
    _TableWidgetForm->getTableWidget()->setItem(0, 0, new QTableWidgetItem(_SmokeConnectStr.name));
    _TableWidgetForm->getTableWidget()->setItem(0, 1, new QTableWidgetItem(_SmokeConnectStr.type));
    m_pTableWidgetFormMap.insert(0,QList<TableWidgetForm*>() << _TableWidgetForm);

    for (int i = 0;i<SmokeSensorstructList.size();i++)
    {
        TableWidgetForm* _TableWidgetForm = new TableWidgetForm(widget);
        splitter->addWidget(_TableWidgetForm);
        _TableWidgetForm->setGroupBoxTitle(QString("%1_%2").arg(fileName.left(fileName.size()-4)).arg(i+1));

        //获取表头
        SmokeSensorstruct _SmokeSensorstructtemp;
        _TableWidgetForm->setTableWidgetHeaderLabels(COMMONS->getTableWidgetHeadLabels(fileName,_SmokeSensorstructtemp.toFieldNames().split(',')));
        _TableWidgetForm->setTableWidgetHeaderType(_SmokeSensorstructtemp.toFieldTypes());

        for (auto item : SmokeSensorstructList.at(i))
        {
            int rowCount = _TableWidgetForm->getTableWidget()->rowCount();
            _TableWidgetForm->getTableWidget()->setRowCount(rowCount+1);
            _TableWidgetForm->getTableWidget()->setItem(rowCount, 0, new QTableWidgetItem(item.name));
            _TableWidgetForm->getTableWidget()->item(rowCount,0)->setData(Qt::UserRole,item.id);
            _TableWidgetForm->getTableWidget()->setItem(rowCount, 1, new QTableWidgetItem(QString("%1").arg(item.alarm)));
            _TableWidgetForm->getTableWidget()->setItem(rowCount, 2, new QTableWidgetItem(QString("%1").arg(item.phyid)));
            _TableWidgetForm->getTableWidget()->setItem(rowCount, 3, new QTableWidgetItem(QString("%1").arg(item.board_id)));
            _TableWidgetForm->getTableWidget()->setItem(rowCount, 4, new QTableWidgetItem(QString("%1").arg(item.port)));
        }
        QList<TableWidgetForm*> item = m_pTableWidgetFormMap.value(0);
        m_pTableWidgetFormMap.insert(0, item << _TableWidgetForm);
    }
}

bool SmokeSensor::SaveUI(const QString &fileName, const QMap<int, QList<TableWidgetForm *> > &m_pTableWidgetFormMap)
{
    QString filePath = QString("%1/config/%2/%3")
            .arg(COMMONS->XmlPath)
            .arg(COMMONS->MachType)
            .arg(fileName);
    if(m_pTableWidgetFormMap.size() > 0)
    {
        SmokeConnectStr _SmokeConnectStr;
        QList<QList<SmokeSensorstruct>> SmokeSensorstructList;
        if(m_pTableWidgetFormMap.value(0).size() > 0)
        {
            TableWidgetForm* _TableWidgetForm = m_pTableWidgetFormMap.value(0).at(0);
            if(_TableWidgetForm)
            {
                _SmokeConnectStr.name = _TableWidgetForm->getTableWidget()->item(0,0)->text();
                _SmokeConnectStr.type = _TableWidgetForm->getTableWidget()->item(0,1)->text();
            }
        }

        for (int i = 1;i<m_pTableWidgetFormMap.value(0).size();i++)
        {
            TableWidgetForm* _TableWidgetForm = m_pTableWidgetFormMap.value(0).at(i);
            if(_TableWidgetForm)
            {
                QList<SmokeSensorstruct> _SmokeSensorstructs;
                for (int k = 0;k<_TableWidgetForm->getTableWidget()->rowCount();k++)
                {
                    SmokeSensorstruct _SmokeSensorstruct;
                    _SmokeSensorstruct.id = _TableWidgetForm->getTableWidget()->item(k,0)->data(Qt::UserRole).toInt();
                    _SmokeSensorstruct.name = _TableWidgetForm->getTableWidget()->item(k,0)->text();
                    _SmokeSensorstruct.alarm = _TableWidgetForm->getTableWidget()->item(k,1)->text().toInt();
                    _SmokeSensorstruct.phyid = _TableWidgetForm->getTableWidget()->item(k,2)->text().toInt();
                    _SmokeSensorstruct.board_id = _TableWidgetForm->getTableWidget()->item(k,3)->text().toInt();
                    _SmokeSensorstruct.port = _TableWidgetForm->getTableWidget()->item(k,4)->text().toInt();
                    _SmokeSensorstructs.append(_SmokeSensorstruct);
                }
                SmokeSensorstructList.append(_SmokeSensorstructs);
            }
        }
        SaveXml(filePath,_SmokeConnectStr,SmokeSensorstructList);
        return true;
    }
    return false;
}

void SmokeSensor::Analysis(const QString &path, SmokeConnectStr &_SmokeConnectStr, QList<QList<SmokeSensorstruct>> &_SmokeSensorstructList)
{
    TiXmlDocument* xmlDocument = new TiXmlDocument();
    if(!xmlDocument->LoadFile(path.toStdString().c_str()))
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return;
    }

    TiXmlElement* rootElement = xmlDocument->FirstChildElement("SmokeSensors");
    if(rootElement == nullptr) //节点不存在
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return;
    }

    if(rootElement)
    {
        TiXmlElement* ConnectStrElement = rootElement->FirstChildElement("ConnectStr");
        if(ConnectStrElement != nullptr)
        {
            _SmokeConnectStr.name = ConnectStrElement->Attribute("name");
            _SmokeConnectStr.type = ConnectStrElement->Attribute("type");
        }

        for(TiXmlElement* GroupElement = rootElement->FirstChildElement("Group");
            GroupElement != nullptr; GroupElement = GroupElement->NextSiblingElement("Group"))
        {
            if(GroupElement != nullptr)
            {
                QList<SmokeSensorstruct> _SmokeSensorstructs;
                for(TiXmlElement* SubGroupElement = GroupElement->FirstChildElement("SmokeSensor");
                    SubGroupElement != nullptr; SubGroupElement = SubGroupElement->NextSiblingElement("SmokeSensor"))
                {
                    SmokeSensorstruct _SmokeSensorstruct;
                    SubGroupElement->QueryIntAttribute("id", &_SmokeSensorstruct.id);
                    _SmokeSensorstruct.name = SubGroupElement->Attribute("name");
                    SubGroupElement->QueryIntAttribute("alarm", &_SmokeSensorstruct.alarm);
                    SubGroupElement->QueryIntAttribute("phyid", &_SmokeSensorstruct.phyid);
                    SubGroupElement->QueryIntAttribute("board_id", &_SmokeSensorstruct.board_id);
                    SubGroupElement->QueryIntAttribute("port", &_SmokeSensorstruct.port);
                    _SmokeSensorstructs.append(_SmokeSensorstruct);
                }
                _SmokeSensorstructList.append(_SmokeSensorstructs);
            }
        }
    }
    delete xmlDocument;
}

bool SmokeSensor::SaveXml(const QString &path, const SmokeConnectStr &_SmokeConnectStr, const QList<QList<SmokeSensorstruct>> &_SmokeSensorstructList)
{
    TiXmlDocument* xmlDocument = new TiXmlDocument();
    if(!xmlDocument->LoadFile(path.toStdString().c_str()))
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return false;
    }

    //查找xml文件中第一个名为Person的节点
    TiXmlElement* rootElement = xmlDocument->FirstChildElement("SmokeSensors");
    if(rootElement == nullptr) //节点不存在
    {
        qDebug() << xmlDocument->ErrorDesc();
        delete xmlDocument;
        return false;
    }

    if(rootElement)
    {
        TiXmlElement* ConnectStrElement = rootElement->FirstChildElement("ConnectStr");
        if(ConnectStrElement != nullptr)
        {
            ConnectStrElement->SetAttribute("name",_SmokeConnectStr.name.toStdString().c_str());
            ConnectStrElement->SetAttribute("type",_SmokeConnectStr.type.toStdString().c_str());
        }

        int index = 0;
        for(TiXmlElement* GroupElement = rootElement->FirstChildElement("Group");
            GroupElement != nullptr; GroupElement = GroupElement->NextSiblingElement("Group"))
        {
            if(GroupElement != nullptr)
            {
                for(TiXmlElement* SubGroupElement = GroupElement->FirstChildElement("SmokeSensor");
                    SubGroupElement != nullptr; SubGroupElement = SubGroupElement->NextSiblingElement("SmokeSensor"))
                {
                    if(SubGroupElement != nullptr)
                    {
                        GroupElement->RemoveChild(SubGroupElement);
                    }
                }

                for (auto _SmokeSensorstruct : _SmokeSensorstructList.at(index))
                {
                    //元素类
                    TiXmlElement* ChildxmlElement = new TiXmlElement("SmokeSensor");
                    ChildxmlElement->SetAttribute("id", _SmokeSensorstruct.id);
                    ChildxmlElement->SetAttribute("name", _SmokeSensorstruct.name.toStdString().c_str());
                    ChildxmlElement->SetAttribute("alarm", _SmokeSensorstruct.alarm);
                    ChildxmlElement->SetAttribute("phyid", _SmokeSensorstruct.phyid);
                    ChildxmlElement->SetAttribute("board_id", _SmokeSensorstruct.board_id);
                    ChildxmlElement->SetAttribute("port", _SmokeSensorstruct.port);
                    GroupElement->LinkEndChild(ChildxmlElement);
                }
                index++;
            }
        }
    }
    //保存
    xmlDocument->SaveFile(path.toStdString().c_str());

    delete xmlDocument;
    return true;
}
